"use client";
import { Button, Textarea } from "@heroui/react";
import {
  startTransition,
  useActionState,
  useEffect,
  useRef,
  useState,
} from "react";
import * as actions from "@/actions";

interface CommentCreateFormProps {
  postId: string;
  isOpen?: boolean;
  parentId?: string;
}

export default function CommentCreateForm({
  postId,
  isOpen,
  parentId,
}: CommentCreateFormProps) {
  // #1
  const [open, setOpen] = useState(isOpen);

  const [state, formAction, isPending] = useActionState(
    actions.createComment.bind(null, { postId, parentId }),
    { errors: {} }
  );
  //提交内容后重置表单[只有成功后充值内容]
  const formRef = useRef<HTMLFormElement>(null);
  useEffect(() => {
    if (state.success) {
      formRef.current?.reset();
    }
  }, [state]);
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.target as HTMLFormElement);
    startTransition(() => formAction(formData));
    setOpen(false)
  };
  return (
    <div className="space-y-3 mt-3">
      <Button onClick={() => setOpen(!open)}>Reply</Button>
      {open && (
        <form
          className="space-y-3"
          onSubmit={handleSubmit}
          noValidate
          ref={formRef}
        >
          <div className="space-y-3">
            <Textarea
              name="content"
              label="Reply"
              labelPlacement="inside"
              placeholder="Enter your comment"
              isInvalid={!!state.errors.content}
              errorMessage={state.errors.content?.join(", ")}
            />
            {state.errors._form ? (
              <div className="p-2 bg-red-200 border rounded border-red-400">
                {state.errors._form?.join(", ")}
              </div>
            ) : null}
            <Button
              color="secondary"
              variant="bordered"
              type="submit"
              isLoading={isPending}
            >
              Create Comment
            </Button>
          </div>
        </form>
      )}
    </div>
  );
}
